/*
 * @描述: 
 * @创建者: kilomChou
 * @Date: 2021-04-11 16:34:02
 * @最后编辑: kilomChou
 * @LastEditTime: 2021-05-15 10:50:08
 */

import GameGlobal from "./GameGlobal";
import World from "./world/World";
import ConnMgr from "./net/ConnMgr";
import IConn from "../core/net/IConn";
import { Proto } from "../data/Proto";
import { VGame } from "../data/XlsxVo";

/** 游戏逻辑端 */
export default class Game {

    constructor() {
        this.world.start();
        /** 开启逻辑端循环 */
        setInterval(() => {
            //计算dt
            let now = Date.now();
            this.global.dt = (now - this._last) * 0.001;
            this._last = now;
            this.update();
        }, 1000 / VGame.cfg.tps);
    }

    /** 游戏全局 */
    readonly global = new GameGlobal();
    /** 世界 */
    readonly world = new World(this.global);
    /** 上一时间，用于计算dt */
    private _last = Date.now();
    /** 连接管理器映射 id->connMgr */
    private _connMgrMap = new Map<number, ConnMgr>();

    /** 每帧循环 */
    update() {
        this.global.timer.addTime(this.global.dt);
        this.world.update();
        this._connMgrMap.forEach(conn => conn.update());
    }

    /** 建立连接 */
    conn(conn: IConn) {
        conn.on(Proto.C2S_JOIN, data => {
            let snakeName = data.name;
            let player = this.world.playerMgr.createPlayer(snakeName);
            conn.id = player.snake.id;
            conn.on(Proto.C2S_READY, data => {
                this._connMgrMap.set(conn.id, new ConnMgr(this, conn, player));
            })
            conn.send(Proto.S2C_JOIN, { id: player.id, worldSize: this.world.size, name: player.name })
        })
    }

    /** 断开连接 */
    disConn(id: number) {
        let conn = this._connMgrMap.get(id);
        if (conn) {
            conn.disConn();
            this._connMgrMap.delete(id);
        }
    }

}